<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="日期选择" prop="stationsCode">
          <el-select
            v-model="queryParams.stationsCode"
            placeholder="请选择站点名称"
            clearable
          >
            <el-option
              v-for="item in stationsList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="当前设备" prop="stationsCode">
          <el-select
            v-model="queryParams.ncurDeviceNo"
            placeholder="请选择站点名称"
            clearable
          >
            <el-option
              v-for="item in deviceNoList"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="primary" icon="Search"
            >搜索</el-button
          >
          <el-button @click="mqtt" type="primary" icon="Search">MQTT</el-button>
          <el-button @click="testDownload" type="primary" icon="Search">下载</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="status"></div>
    <el-card
      ><!-- 曲线 -->
      <el-row>
        <el-col :span="24">
          <el-card
            ><!-- 数据表格 -->
            <el-table
              max-height="600"
              :data="tableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column label="序号" type="index" width="150" />

              <el-table-column label="时间" align="center" prop="ts" />
              <el-table-column label="变量名" align="center" prop="m" />
              <el-table-column label="变量值" align="center" prop="v" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted, watch, nextTick } from "vue";
const tableData = ref(); //表格数组
const stationsList = reactive([
  {
    label: "本地场站",
    value: 0,
  },
]);
const deviceNoList = ref([]);
const queryParams = reactive({
  stationsCode: null,
  devInfoCode: "",
  pointCode: "",
  ncurDeviceNo: null,
});

const websocket = ref();
// WebSocket连接函数
const connectWebSocket = () => {
  // 替换为您的实际WebSocket地址
  websocket.value = new WebSocket("ws://localhost:8800/mqtt-stream");

  websocket.value.onopen = () => {
    console.log("WebSocket-mqtt连接已建立");
  };

  websocket.value.onmessage = (event) => {
    try {
      // 解析接收到的JSON数据
      const data = JSON.parse(event.data);
      // 转换为JavaScript对象
      const dataObj = JSON.parse(data.content);

      // 现在可以直接访问对象的属性
      console.log("原始数据", dataObj);

      console.log("版本号：", dataObj.ver); // 输出：2.2.10
      console.log("设备编号：", dataObj.pKey); // 输出：TS-001
      console.log("第一个设备：", dataObj.devs[0].dev); // 输出：PCS01
      console.log("第一个设备的第一个参数：", dataObj.devs[0].d); // 输出：P
      deviceNoList.value = dataObj.devs?.map((it) => it.dev);
      // if(deviceNoList.value.length > 0){
      //   queryParams.ncurDeviceNo = deviceNoList.value[0];
      // }
      // tableData.value = data;
      const matchedDev = dataObj.devs?.find(
        (it) => it.dev === queryParams.ncurDeviceNo
      );
      tableData.value = matchedDev ? matchedDev.d : []; // 若找到则赋值d，否则赋值空数组
      console.log(tableData.value, "xxxx");
    } catch (error) {
      console.error("解析WebSocket消息出错:", error);
    }
  };

  websocket.value.onclose = () => {
    console.log("WebSocket连接已关闭");
    // 可以在这里实现重连逻辑
  };

  websocket.value.onerror = (error) => {
    console.error("WebSocket错误:", error);
  };
};
async function testDownload() {
  const statusDiv = document.getElementById("status");
  const blobUrl =
    "blob:http://192.168.1.127/6e08b51f-60ee-42db-962f-deae833a7bf1";

  try {
    statusDiv.innerHTML = "Starting download...";

    const response = await fetch(blobUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);

    const a = document.createElement("a");
    a.style.display = "none";
    a.href = url;
    a.download = "downloaded-file"; // You can set a specific filename here

    document.body.appendChild(a);
    a.click();

    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    statusDiv.innerHTML = "Download completed successfully!";
  } catch (error) {
    statusDiv.innerHTML = `Error: ${error.message}`;
    console.error("Download failed:", error);
  }
}
onMounted(() => {
  connectWebSocket();
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.dv-scroll-board .header) {
  background: #ddd !important;
}
:deep(.dv-scroll-board .rows .row-item) {
  background: gray !important;
}
</style>
